package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ISkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.domain.SkuLockVo;
import com.spzx.product.vo.SkuStockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author biu
 * @since 2025-03-13
 */
@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SkuStockVo getSkuStock(Long skuId) {

        //查询数据
        LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SkuStock::getSkuId, skuId);
        queryWrapper.select(SkuStock::getAvailableNum, SkuStock::getSaleNum);
        SkuStock skuStock = baseMapper.selectOne(queryWrapper);

        //封装数据
        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setSkuId(skuId);
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        skuStockVo.setSaleNum(skuStock.getSaleNum());

        return skuStockVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = baseMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if(skuStock == null){
                skuLockVo.setHaveStock(false);//没有库存
            }else{
                skuLockVo.setHaveStock(true);//有库存
            }
        }

        //只要有一个库存不足
        if(skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.isHaveStock())){
            //过滤出所有库存不足的商品
            List<SkuLockVo> list = skuLockVoList
                    .stream()
                    .filter(skuLockVo -> !skuLockVo.isHaveStock())
                    .toList();

            //组装所有list中的商品名skuName
            StringBuffer resultMessage = new StringBuffer();
            list.forEach(skuLockVo -> {
                resultMessage
                        .append(skuLockVo.getSkuName())
                        .append(": ").
                        append(skuLockVo.getSkuNum())
                        .append("\n");
            });

            return resultMessage.append("库存不足").toString();
        }else{

            for (SkuLockVo skuLockVo : skuLockVoList) {
                //锁定库存
                baseMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }

            String dataKey = "sku:lock:data:" + orderNo;
            redisTemplate.opsForValue().set(dataKey, skuLockVoList);

            return "";
        }
    }


    //解锁库存
    @Override
    public void unlock(String orderNo) {
        //幂等性处理
        String Key = "sku:unlock" +orderNo;
        Boolean isFirst = redisTemplate.opsForValue().setIfAbsent(Key, orderNo, 30, TimeUnit.SECONDS);
        if(!isFirst) return;

        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if(!CollectionUtils.isEmpty(skuLockVoList)){
            for(SkuLockVo skuLockVo : skuLockVoList){
                baseMapper.unlock(skuLockVo.getSkuId(),skuLockVo.getSkuNum());
            }
        }
        redisTemplate.delete(dataKey);
    }

    @Override
    public void minus(String orderNo) {

        //幂等性处理
        String key = "sku:minus:"+ orderNo;
        Boolean isFirst = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 30, TimeUnit.SECONDS);
        if(!isFirst) return;

        log.error("执行。。。。。");
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if(!CollectionUtils.isEmpty(skuLockVoList)){
            for (SkuLockVo skuLockVo : skuLockVoList) {
                baseMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }
        }
        //删除redis中的数据
        redisTemplate.delete(dataKey);

    }
}
